﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media.Animation;
using Samurai.WorkflowGraph.EventArgs;
using Samurai.WorkflowGraph.Models;
using Samurai.WorkflowGraph.ViewModels;
using Telerik.Windows.Controls;

namespace Samurai.WorkflowGraph.Views
{
    /// <summary>
    /// Interaction logic for WorkflowGraphView.xaml
    /// </summary>
    public partial class WorkflowGraphView
    {
        private readonly WorkflowLayoutAlgorithm _layoutAlgorithm = new WorkflowLayoutAlgorithm();
        private readonly Storyboard _collapseStoryboard;
        private readonly Storyboard _showStoryboard;

        /// <summary>
        /// Initializes a new instance of the <see cref="WorkflowGraphView"/> class.
        /// </summary>
        public WorkflowGraphView()
        {
            InitializeComponent();

            _collapseStoryboard = Resources["Collapse"] as Storyboard;
            _showStoryboard = Resources["Show"] as Storyboard;
            DataContextChanged += OnContextChanged;
        }

        public WorkflowGraphViewModel ViewModel
        {
            get
            {
                if(DataContext == null)
                    throw new InvalidOperationException("No DataContext present.");

                return (WorkflowGraphViewModel) DataContext;
            }
        }

        private void OnContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            ViewModel.NodeVisibilityChanged += ViewModelNodeVisibilityChanged;
        }

        private void OnDiagramSizeChanged(object sender, SizeChangedEventArgs e)
        {
            RefreshDiagramLayout();
        }

        private void RefreshDiagramLayout()
        {
            _layoutAlgorithm.Layout(WorkflowDiagram);
            WorkflowDiagram.AutoFit();
        }

        private void ViewModelNodeVisibilityChanged(object sender, VisibilityChangedEventArgs e)
        {
            var node = sender as WorkflowStepNode;
            var container = WorkflowDiagram.ContainerGenerator.ContainerFromItem(node) as RadDiagramShape;
            Debug.Assert(container != null);
#if SILVERLIGHT
            if (e.IsVisible)
            {
                container.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                container.Visibility = System.Windows.Visibility.Collapsed;
            }
#else
            Storyboard.SetTarget(_collapseStoryboard, container);
            Storyboard.SetTarget(_showStoryboard, container);
            if (e.IsVisible)
            {
                _showStoryboard.Begin();
            }
            else
            {
                _collapseStoryboard.Begin();
            }
#endif
        }
    }
}
